/*
 * @Author: xianfuyou
 * @Date: 2022-03-31 15:59:17
 * @LastEditors: your name
 * @LastEditTime: 2022-04-11 17:09:35
 * @Description: file content
 */
import React, { useCallback, useEffect, useRef, useState } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import ButtonWarpCpn from '../../../components/CommBtn/CommBtn'

import {
  Row,
  Col,
  Form,
  Input,
  Select,
  Button,
  DatePicker,
  Table,
  Modal,
  Upload, message, Tag
} from 'antd'
import { QuestionCircleFilled, PlusSquareFilled, CloseCircleFilled, PlusCircleFilled, DeleteFilled } from '@ant-design/icons';
import './FillOrder.css'
import '../../../components/OrderCpn/css/Model.css'
import AddLinkman from '../../../components/OrderCpn/AddLinkman';
import Axios from '../../../utils/http'
import Qs from 'qs'

const { TextArea } = Input;

export default function FillOrder() {
  // const baseUrl = 'http://139.155.237.161:8080'
  // 当前客户
  const [custormer, setCustormer] = useState(null)
  // 文件上传列表
  const [AccessfileList, setAccessFileList] = useState([])
  // 新增联系人
  const [addLinkman, setAddLinkman] = useState(false)
  // 保存自动生成的订单编号
  const [orderNumber, setOrderNumber] = useState(null)
  // 商品删除弹窗
  const [delModel, setDelModel] = useState(false)
  // 保存删除的商品
  const [delGoodsObj, setDelGoodsObj] = useState({})
  // 商品明细列表
  const [goodsList, setGoodsList] = useState([
    {
      key: 1,
      id: 1,
      goodsName: `可乐`,
      size: ``,
      type: ``,
      cost: `50`,
      salePrice: '100',
      count: `200`,
      discount: '13135',
      priceAll: `1231`,
      remark: `212312312sadasd`,
      enterTime: `2022-03-30`,
    }, {
      key: 2,
      id: 2,
      goodsName: `雪碧`,
      size: ``,
      type: ``,
      cost: `50`,
      salePrice: '123',
      count: `200`,
      discount: '13135',
      priceAll: `1231`,
      remark: `212312312sadasd`,
      enterTime: `2022-03-30`,
    }
  ])
  // 获取表单内容
  const [form] = Form.useForm();

  const navigate = useNavigate()
  const { state: userInfo } = useLocation()


  useEffect(() => {
    console.log(userInfo)
    // 这里假装发个请求接收到数据
    getOrderNumber()
  }, [])

  // 获取后台返回的唯一订单编号
  const getOrderNumber = () => {
    Axios.post('/order/getOderNumber',
      Qs.stringify({ id: 2 }),
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } })
      .then(res => {
        console.log(res)
        if (res.data.code === 200) {
          setCustormer(res.data.data.customerUser[0])
          setOrderNumber(res.data.data.uuid)
          form.setFieldsValue({ 'orderId': res.data.data.uuid })
        }
      })
  }

  // 表单配置
  const checkGoodsTable = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: 50,
      render: (id) => {
        return <span style={{ color: '#f20000' }}>{id}</span>
      }
    },
    {
      title: '商品名称',
      dataIndex: 'goodsName',
      key: 'goodsName',
      width: 120,
    },
    {
      title: '规格',
      dataIndex: 'size',
      key: 'size',
      width: 80,
    },
    {
      title: '型号',
      dataIndex: 'type',
      key: 'type',
      width: 80,
    },
    {
      title: '成本',
      dataIndex: 'cost',
      key: 'cost',
      width: 100,
    },
    {
      title: '售价',
      dataIndex: 'salePrice',
      key: 'salePrice',
      width: 100,
      editable: true,
      render: (salePrice, record) => {
        return <Input onChange={(e) => { updataData(e)(record.id, 'salePrice') }} value={salePrice}></Input>
      }
    },
    {
      title: '数量',
      dataIndex: 'count',
      key: 'count',
      width: 100,
      render: (count, record) => {
        return <Input onChange={(e) => { updataData(e)(record.id, 'count') }} value={count}></Input>
      }
    },
    {
      title: '折扣',
      dataIndex: 'discount',
      key: 'discount',
      width: 100,
      render: (discount, record) => {
        return <Input onChange={(e) => { updataData(e)(record.id, 'discount') }} value={discount}></Input>
      }
    },
    {
      title: '总金额',
      dataIndex: 'priceAll',
      key: 'priceAll',
      width: 100,
      render: (priceAll) => {
        return <Input value={priceAll} disabled></Input>
      }
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: 150,
      render: (remark, record) => {
        return <Input onChange={(e) => { updataData(e)(record.id, 'remark') }} value={remark}></Input>
      }
    },
    {
      title: '录入时间',
      dataIndex: 'enterTime',
      key: 'enterTime',
      width: 100,
    },
    {
      title: '管理',
      dataIndex: 'manager',
      key: 'manager',
      width: 80,
      render: (manager, record) => {
        return <DeleteFilled onClick={() => { delAGood(record) }} style={{ 'color': '#d20000', cursor: 'pointer', fontSize: '16px' }} />
      }
    }
  ]

  // 更新表格中内容
  const updataData = (e) => {
    return (id, type) => {
      let newLists = goodsList.map(item => {
        if (item.id === id) {
          item[type] = e.target.value
        }
        return item
      })
      setGoodsList(newLists)
    }
  }

  // 删除新增的商品数据
  const delAGood = (data) => {
    // console.log(data)
    setDelGoodsObj(data)
    setDelModel(true)
  }

  // 确定删除商品
  const delGoodOk = () => {
    setDelModel(false)
    console.log(delGoodsObj)
  }

  // 表单部分
  // 提交表单获取表单内容
  const onFinish = () => {
    // console.log('form', form.getFieldsValue())
    const nowFormData = form.getFieldsValue()
    const resValues = {
      ...nowFormData,
      "downOrderDate": nowFormData['downOrderDate'] && nowFormData['downOrderDate'].format('YYYY-MM-DD HH:mm:ss'),
      "enterOrderDate": nowFormData['enterOrderDate'] && nowFormData['enterOrderDate'].format('YYYY-MM-DD HH:mm:ss'),
    }
    console.log('resValues', resValues);
  };
  // 重置表单
  const onBack = () => {
    form.resetFields();
    navigate('/order/addOrderComm')
  }

  // 上传文件
  const handleChange = info => {
    console.log(info)
    putFile(info.file)
    // let fileList = [...info.fileList];
    // fileList = fileList.slice(-2);
    // fileList = fileList.map(file => {
    //   if (file.response) {
    //     file.url = file.response.url;
    //   }
    //   return file;
    // });
    // console.log('fileList', fileList)
    // setAccessFileList(fileList)
  };
  // 上传附件
  const putFile = (nowfile) => {
    console.log(nowfile)
    let formData = new FormData()
    formData.append('file', nowfile)
    Axios.post('/orderEnclosure/insertEnclosureById',
      { formData })
      .then(res => {
        console.log(res)
      })
  }
  // 新增联系人
  const changeLinkman = () => {
    setAddLinkman(true)
  }

  // 选择文件上传
  const props = {
    action: '',
    onChange: handleChange,
    multiple: true,
  };

  return (
    <div className={'fillOrder'}>
      {/*  */}
      {/* 新增联系人弹窗 */}
      <AddLinkman isShow={addLinkman} pOk={(res) => { setAddLinkman(res) }} pCancel={(res) => { setAddLinkman(res) }}></AddLinkman>
      <Modal
        className='xfy_dep_add_modal del_modal del_product_modal'
        title="消息"
        okText="确定"
        cancelText="取消"
        visible={delModel}
        onOk={delGoodOk}
        onCancel={() => { setDelModel(false) }}
        destroyOnClose={true}
        forceRender={true}
        zIndex={2000}
      >
        <Row align='middle' gutter={10}>
          <Col> <CloseCircleFilled style={{ color: '#faa685', fontSize: '36px' }} /></Col>
          <Col> <span>是否确定删除? 删除后将退回该商品库存！</span></Col>
        </Row>

      </Modal>
      {/* 添加订单表单 */}
      <Row className={'highFrom'}>
        <Col className={'title'}>新增订单管理</Col>
        <Col className={"flag"} span={24}>
          <Row justify={'space-between'} align={'middle'}>
            <Col span={24}>
              <Form
                labelCol={{
                  span: 8,
                }}
                wrapperCol={{
                  span: 16,
                }}
                form={form}
                name="control-ref" onFinish={onFinish}
              >
                {/* 表单部分 */}
                <Row className="fromDataSection">
                  <Col span={8}>
                    <Form.Item label="订单编号">
                      <Row>
                        <Col span={16}>
                          <Form.Item name="orderId">
                            <Input size="small" style={{ color: '#000' }} disabled />
                          </Form.Item>
                        </Col>
                        <Col span={8}>
                          <Form.Item className={""}>
                            <Row className={"ordercomment"} align={'middle'}>
                              <Col>
                                <span style={{ display: "inline-block" }}>
                                  <QuestionCircleFilled style={{ fontSize: '16px', margin: '4px 5px 0px' }} />
                                </span>
                              </Col>
                              <Col>
                                <span>自动编号</span>
                              </Col>
                            </Row>
                          </Form.Item>
                        </Col>
                      </Row>
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span={8}>
                    <Form.Item label="客户名称" name="clientName">
                      <span>{custormer && custormer.name}<Button size="small" type="primary" danger style={{ marginLeft: '5px', backgroundColor: '#d55866', border: '0px' }}>重选</Button></span>
                    </Form.Item>
                    <Form.Item label="订单总金额">
                      <Row align="middle">
                        <Col span={8}>
                          <Form.Item name="service">
                            <Input size="small" />
                          </Form.Item>
                        </Col>
                        <Col span={16}>
                          <Form.Item>
                            <span className={"ordercomment"}><span style={{ color: '#000' }}>元</span><QuestionCircleFilled style={{ fontSize: '16px', margin: '4px 5px 0px' }} /><span>结果自动计算</span></span>
                          </Form.Item>
                        </Col>
                      </Row>
                    </Form.Item>
                    <Form.Item label="下单日期" name="downOrderDate">
                      <DatePicker size="small" />
                    </Form.Item>
                    <Form.Item wrapperCol={{ span: 6 }} label="收货人" name="putawayPerson">
                      <Input size="small" />
                    </Form.Item>
                  </Col>
                  <Col span={8} offset={2}>
                    <Form.Item label="联系人">
                      <Row>
                        <Col span={9}>
                          <Form.Item name="linkman">
                            <Select size="small">
                              <Select.Option value="demo">Demo</Select.Option>
                            </Select>
                          </Form.Item>
                        </Col>
                        <Col style={{ marginLeft: '5px' }}>
                          <Form.Item>
                            <ButtonWarpCpn onClick={() => { changeLinkman() }} bgcolor="#5cad69" icon={<PlusSquareFilled />}>新增</ButtonWarpCpn>
                          </Form.Item>
                        </Col>
                      </Row>
                    </Form.Item>
                    <Form.Item wrapperCol={{ span: 6 }} label="已收款" name="unPayOver">
                      <Input size="small" />
                    </Form.Item>
                    <Form.Item label="交单日期" name="enterOrderDate">
                      <DatePicker size="small" />
                    </Form.Item>
                    <Form.Item wrapperCol={{ span: 10 }} label="收货人电话" name="putawayPersonTel">
                      <Input size="small" />
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span={8}>
                    <Form.Item label="收货人地址" name="putawayAddress">
                      <Input size="small" />
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span={8}>
                    <Form.Item label="附件" name="accessory">
                      <Upload {...props} fileList={AccessfileList}>
                        <ButtonWarpCpn bgcolor="#00b7ee" size="small">选择文件</ButtonWarpCpn>
                      </Upload>
                    </Form.Item>
                  </Col>
                </Row>
                <Row>
                  <Col span={8}>
                    <Form.Item label="备注" name="remark">
                      <TextArea rows={4} placeholder="maxLength is 6" maxLength={6} />
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </Col>
          </Row>
        </Col>
      </Row>
      {/* 添加商品接口 */}
      <Row className={'totalCount'} justify="space-between">
        <Col style={{ fontWeight: 'bold' }}>商品明细</Col>
        <Col className={'count'}>
          成本总合：<span>2478元</span> 售价总合：<span>2478元</span> 数量总合：<span>28</span> 折扣总合：<span>0元</span> 最终总金额：<span>8300元</span>
        </Col>
        <Col>
          <ButtonWarpCpn bgcolor="#009966" size="small" icon={<PlusCircleFilled />}>新增商品</ButtonWarpCpn>
        </Col>
      </Row>
      {/* 选择商品表单 */}
      <Row className={'goodsLists'}>
        <Col span={24}>
          <Table
            pagination={false}
            size="small"
            columns={checkGoodsTable}
            dataSource={goodsList}
          />
        </Col>
      </Row>
      {/* 处理业务员 保存及取消*/}
      <Row className={'salesmanAndSave'} justify="space-between">
        <Col>
          <span style={{ marginRight: '5px' }}>业务员</span>
          <Tag color="#0099cc">超级管理员</Tag>
        </Col>
        <Col className={'saveHandle'}>
          <ButtonWarpCpn onClick={onFinish} size="small" bgcolor="#448aca">保存</ButtonWarpCpn>
          <ButtonWarpCpn onClick={onBack} size="small" bgcolor="#505050">返回</ButtonWarpCpn>
        </Col>
      </Row>
    </div>
  )
}
